package demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Resource extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static SamlConsumer consumer = new SamlConsumer();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse) this get hits once the
	 * app_url/resource is called
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) {

		String resourceUrl = null;
		String completeRedirectUrl = null;

		try {

			resourceUrl = request.getRequestURL().toString();
			completeRedirectUrl = consumer.buildAuthnRequestMessage(resourceUrl);
			response.sendRedirect(completeRedirectUrl);

		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) {

		PrintWriter out = null;
		String responseMessage = null;
		String result = null;
		String[] resultArray = null;
		String status = null;
		String user = null;

		try {

			out = response.getWriter();

		} catch (IOException e) {

			e.printStackTrace();
		}

		responseMessage = request.getParameter("SAMLResponse").toString();
		result = consumer.processResponseMessage(responseMessage);

		resultArray = result.split(":");
		user = resultArray[0];
		status = resultArray[1];

		if (status.equals("Success")) {

			out.println("Authentication successfull. Redirrection !");
			request.getSession().setAttribute("userName", user);

			try {

				response.sendRedirect("home.jsp");

			} catch (IOException e) {

				e.printStackTrace();
			}

		} else {

			out.println("\n" + user + " authentication failed \n");
		}

	}
}
